<template>
  <div class="app-container">
    <el-steps :active="progress" finish-status="success" :align-center="true">
      <el-step title="提交申请"></el-step>
      <el-step title="审核"></el-step>
      <!-- <el-step title="缴纳保证金"></el-step> -->
    </el-steps>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>申请资料</span>
      </div>
      <el-form ref="form" :model="form" label-width="120px" :rules="rules">
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" :disabled="progress!=0"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="cardNumber">
          <el-input v-model="form.cardNumber" :disabled="progress!=0"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input type="tel" v-model="form.phone" :disabled="progress!=0"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input type="email" v-model="form.email" :disabled="progress!=0"></el-input>
        </el-form-item>
        <el-form-item label="商家地址" prop="address">
          <el-input type="textarea" v-model="form.address" :disabled="progress!=0"></el-input>
        </el-form-item>
        <el-form-item label="主体类型" prop="businessType">
          <el-select v-model="form.businessType" placeholder="请选择经营主体类型" :disabled="progress!=0">
            <el-option v-for="dict in dict.type.business_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="营业执照" prop="licenseUrl">
          <img v-if="licenseImage" :src="licenseImage" class="el-upload--picture-car" v-show="progress!=0"/>
          <el-upload
             v-show="progress==0"
            :action="uploadImgUrl"
            :headers="headers"
            :on-success="getLicenseUrl"
            :before-upload="limitImg"
            :show-file-list="false"
            :limit="1"
            drag
            accept="image/jpg,image/jpeg,image/png">
            <img v-if="licenseImage" :src="licenseImage" class="el-upload--picture-car" />
            <div v-else>
              <i class="el-icon-picture" style="margin-top: 40px; font-size: 40px; color: #999a9c"></i>
              <div>上传营业执照图片</div>
              <div>格式为png、jpeg或jpg</div>
            </div>
          </el-upload>
          <img v-if="noEdit" :src="licenseImage" class="el-upload--picture-car" />
        </el-form-item>
        <el-form-item label="身份证正反面">
          <div>
            <img :src="cardFrontImage" class="el-upload--picture-car" v-show="progress!=0" style="margin-right: 20px;"/>
            <img :src="cardBackImage" class="el-upload--picture-car" v-show="progress!=0"/>
          </div>
          <div style="display: flex;">
            <el-upload style="margin-right: 20px;"
            v-show="progress==0"
            :action="uploadImgUrl"
            :headers="headers"
            :on-success="getCardFrontUrl"
            :before-upload="limitImg"
            :show-file-list="false"
            :limit="1"
            drag
            accept="image/jpg,image/jpeg,image/png">
              <i v-if="cardFrontImage" class="el-icon-circle-close deleteImg"></i>
              <img v-if="cardFrontImage" :src="cardFrontImage" class="el-upload--picture-car" />
              <div v-else>
                <i class="el-icon-picture" style="margin-top: 40px; font-size: 40px; color: #999a9c"></i>
                <div>上传身份证正面</div>
                <div>格式为png、jpeg或jpg</div>
              </div>
            </el-upload>
              <el-upload 
              v-show="progress==0"
              :action="uploadImgUrl"
              :headers="headers"
              :on-success="getCardBackUrl"
              :before-upload="limitImg"
              :show-file-list="false"
              :limit="1"
              drag
              accept="image/jpg,image/jpeg,image/png">
              <i v-if="cardBackImage" class="el-icon-circle-close deleteImg"></i>
              <img v-if="cardBackImage" :src="cardBackImage" class="el-upload--picture-car" />
              <div v-else>
                <i class="el-icon-picture" style="margin-top: 40px; font-size: 40px; color: #999a9c"></i>
                <div>上传身份证反面</div>
                <div>格式为png、jpeg或jpg</div>
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" v-show="progress==0">提交申请</el-button>
          <el-button @click="resetForm" v-show="progress==0">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>缴纳保证金</span>
      </div>
      <div>
        
      </div>
    </el-card> -->
  </div>

</template>
  
  <script>
  import { submitData,getFormData } from '@/api/business/business'

  export default {
    dicts:['business_type'],
    data() {
      return {
        progress:0,
        appState:"",
        noEdit:false,
        form: {
          realName: '',
          cardNumber:'',
          phone: '',
          email: '',
          address: '',
          licenseUrl:null,
          cardFrontUrl:null,
          cardBackUrl:null,
        },
        rules:{
          realName: [
            { required: true, message: '请输入真实姓名', trigger: 'blur' }
          ],
          cardNumber: [
            { required: true, message: '请输入身份证号', trigger: 'blur' },
            { validator: this.validateIdCard, trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '请输入联系电话', trigger: 'blur' },
            { validator: this.validatePhoneNumber, trigger: 'blur' }
          ],
          email:[
            { required: true, message: '请输入电子邮箱', trigger: 'blur' },
            { validator: this.validateEmail, trigger: 'blur' },
          ]
        },
        uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
        headers:{
          Authorization: "Bearer " + this.$store.getters.token
        },
        licenseImage:"",
        cardFrontImage:"",
        cardBackImage:""
      };
    },
    created(){
      this.getState()
    },
    methods: {
      getState(){
        getFormData(this.$store.state.user.id).then(res => {
          if(res.code==200){
            console.log(res)
              this.progress = parseInt(res.data.state)
              this.form = res .data
              this.licenseImage = process.env.VUE_APP_BASE_API + this.form.licenseUrl
              this.cardFrontImage = process.env.VUE_APP_BASE_API + this.form.cardFrontUrl
              this.cardBackImage = process.env.VUE_APP_BASE_API + this.form.cardBackUrl
          }
        })
      },
       // 身份证号验证方法
    validateIdCard(rule, value, callback) {
      // 正则表达式，验证身份证格式是否正确
      const idCardReg = /^\d{17}(\d|X|x)$/;
      if (!value) {
        return callback(new Error('请输入身份证号'));
      }
      if (!idCardReg.test(value)) {
        return callback(new Error('身份证号格式不正确'));
      }

      // 校验身份证号的最后一位
      if (!this.isValidIdCard(value)) {
        return callback(new Error('身份证号校验位不正确'));
      }

      callback();
    },

    // 校验身份证号的校验位
    isValidIdCard(idCard) {
      // 身份证号前17位加权因子
      const weightFactors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
      // 校验位对应值
      const validCheckCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
      
      let sum = 0;
      for (let i = 0; i < 17; i++) {
        sum += parseInt(idCard[i]) * weightFactors[i];
      }

      const checkCodeIndex = sum % 11;
      const checkCode = validCheckCodes[checkCodeIndex];
      
      // 判断身份证号的第18位是否与计算出的校验位一致
      return idCard[17].toUpperCase() === checkCode;
    },

    // 手机号验证方法
    validatePhoneNumber(rule, value, callback) {
      // 手机号正则表达式，匹配以 1 开头，第二位是 3-9 之间的数字，后面是 9 位数字
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!value) {
        return callback(new Error('请输入手机号'));
      }
      if (!phoneReg.test(value)) {
        return callback(new Error('手机号格式不正确'));
      }
      callback();
    },

     // 电子邮箱验证方法
     validateEmail(rule, value, callback) {
      // 正则表达式验证电子邮箱格式
      const emailReg = /^[a-zA-Z0-9_-]+([.][a-zA-Z0-9_-]+)*@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (!value) {
        return callback(new Error('请输入电子邮箱'));
      }
      if (!emailReg.test(value)) {
        return callback(new Error('电子邮箱格式不正确'));
      }
      callback();
    },
      submitForm() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.form.businessId = this.$store.state.user.id
            console.log(this.$store.state.user)
            submitData(this.form).then(res=>{
              this.$modal.msgSuccess("提交成功,请耐心等待审核！注意查收邮件提醒！");
              this.getState()
            }).catch(error => {
              this.$modal.msgError(successMessage + "失败");
            });
          } else {
            console.log('error submit!!');
            this.$modal.msgError("请检查输入的信息是否有误！");
            return false;
          }
        });
      },
      resetForm(){
        this.$refs.form.resetFields();
        this.licenseImage = '';
        this.cardFrontImage = '';
        this.cardBackImage = '';
      },
      limitImg(file){
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
        if (!isJPG) {
          this.$modal.msgError("上传图片只能是 JPG、PNG、JPEG 格式!");
          return false;
        }
      },
      getLicenseUrl(res, file){
        console.log(res)
        if(res.code !== 200){
          this.$modal.msgError("上传图片出错，请重新上传！");
          return false;
        }
        this.form.licenseUrl = res.fileName
        this.licenseImage = process.env.VUE_APP_BASE_API + res.fileName
      },
      getCardFrontUrl(res,file){
        if(res.code !== 200){
          this.$modal.msgError("上传图片出错，请重新上传！");
          return false;
        }
        this.form.cardFrontUrl = res.fileName
        this.cardFrontImage = process.env.VUE_APP_BASE_API + res.url
      },
      getCardBackUrl(res,file){
        if(res.code !== 200){
          this.$modal.msgError("上传图片出错，请重新上传！");
          return false;
        }
        this.form.cardBackUrl = res.fileName
        this.cardBackImage = process.env.VUE_APP_BASE_API + res.url
      },
      changeLicense(item){
        this.licenseImage = URL.createObjectURL(item.raw); // 图片上传浏览器回显地址
      },
      uploadCardFront(item){
        this.form.cardFrontFile = item.raw
        this.cardFrontImage = URL.createObjectURL(item.raw);
      },
      uploadCardBack(item){
        this.form.cardBackFile = item.raw
        this.cardBackImage = URL.createObjectURL(item.raw);
      }
    }
  };
  </script>
  
  <style>
  .box-card {
    width: 80%;
    margin: 20px auto;
  }
  /* 可以在这里添加一些自定义样式 */
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
  </style>